package com.szboanda.execution;

import org.apache.commons.lang.StringUtils;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据库连接类
 * 
 * @author zhangsheng
 * 
 */
public class ConnectionWrapper {

    /**
     * 创建数据库连接对象
     */
    private Connection connection;

    /**
     * 创建PreparedStatement对象
     */
    private PreparedStatement preparedStatement;

    /**
     * 创建CallableStatement对象
     */
    private CallableStatement callableStatement;

    /**
     * 创建结果集对象
     */
    private ResultSet resultSet;

    /**
     * 查询超时时间
     */
    private int queryTimeOut = -1;

    /**
     * 行记录标识
     */
    private final static String ROW_FLAG = "RN";

    /**
     *  是否需要行号
     */
    private boolean needRowNum = false;

    /**
     *
     * @param connection
     */
    public ConnectionWrapper(Connection connection) {
        this.connection = connection;
    }

    /**
     * 带连接、查询超时的构造
     * @param connection
     * @param queryTimeOut
     */
    public ConnectionWrapper(Connection connection, int queryTimeOut) {
        this.connection = connection;
        this.queryTimeOut = queryTimeOut;
    }

    /**
     * 带连接、查询超时的构造
     * @param connection
     * @param queryTimeOut
     * @param needRowNum
     */
    public ConnectionWrapper(Connection connection, int queryTimeOut, boolean needRowNum) {
        this.connection = connection;
        this.queryTimeOut = queryTimeOut;
        this.needRowNum = needRowNum;
    }


    /**
     * insert update delete 自动关闭连接
     * 
     * @param sql SQL语句
     * @param params 参数数组，若没有参数则为null
     * @return 受影响的行数
     */
    public int executeUpdate(String sql, Object... params) throws SqlExecutionException {
        // 受影响的行数
        int affectedLine = 0;

        try {
            // 调用SQL
            preparedStatement = connection.prepareStatement(sql);
            // 参数赋值
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    preparedStatement.setObject(i + 1, transformType(params[i]));
                }
            }

            // 执行
            affectedLine = preparedStatement.executeUpdate();

        } catch (SQLException e) {
            throw new SqlExecutionException("sql=" + sql + "param" + Arrays.toString(params), e);
        } finally {
            // 释放资源
            closeAll();
        }
        return affectedLine;
    }

    /**
     * 多条语句放在一个事务中执行
     * 
     * @param sqls
     * @param params
     * @return
     * @throws SqlExecutionException
     */
    public int executeUpdate(List<String> sqls, List<Object[]> params) throws SqlExecutionException {
        // 受影响的行数
        int affectedLine = 0;
        if (null == sqls || sqls.isEmpty()) {
            return affectedLine;
        }
        try {
            // 获得连接
            connection.setAutoCommit(false);
            for (int i = 0; i < params.size(); i++) {
                if (null == sqls.get(i)) {
                    continue;
                }
                // 调用SQL
                preparedStatement = connection.prepareStatement(sqls.get(i));

                // 参数赋值
                if (params.get(i) != null) {
                    for (int j = 0; j < params.get(i).length; j++) {
                        preparedStatement.setObject(j + 1, transformType(params.get(i)[j]));
                    }
                }
                // 执行
                affectedLine = preparedStatement.executeUpdate();
                //长时间不释放会超过游标
                preparedStatement.close();
            }
            connection.commit();
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException e1) {
                throw new SqlExecutionException("sql=" + sqls.toString() + "param" + this.toString(params), e1);
            }
            throw new SqlExecutionException("sql=" + sqls.toString() + "param" + this.toString(params), e);
        } finally {
            // 释放资源
            closeAll();
        }

        return affectedLine;
    }
   
    /**
     * 数组toString
     * 
     * @param objs
     * @return
     */
    private String toString(Object... objs) {
        StringBuilder sbr = new StringBuilder(256);
        for (int i = 0; i < objs.length; i++) {
            sbr.append(this.toString(objs[i]) + ",");
            sbr.append(',');
        }
        return sbr.toString();
    }
    
    /**
     * Object 对象转换为string
     * 
     * @param obj
     * @return
     */
    public String toString(Object obj) {
        return obj == null ? "" : String.valueOf(obj);
    }

    /**
     * 数组toString
     * @param params
     * @return
     */
    private String toString(List<Object[]> params) {
        StringBuilder sbr = new StringBuilder(256);
        for (int i = 0; i < params.size(); i++) {
            sbr.append('\n');
            sbr.append(this.toString(params.get(i)));
        }
        return sbr.toString();
    }

    /**
     * SQL 查询将查询结果直接放入ResultSet中
     * 
     * @param sql SQL语句
     * @param params 参数数组，若没有参数则为null
     * @return 结果集
     */
    private ResultSet executeQueryRS(String sql, Object... params) throws SqlExecutionException {
        try {
            // 调用SQL
            preparedStatement = connection.prepareStatement(sql);
            if (queryTimeOut != -1) {
                preparedStatement.setQueryTimeout(queryTimeOut);
            }
            // 参数赋值
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    preparedStatement.setObject(i + 1, transformType(params[i]));
                }
            }

            // 执行
            resultSet = preparedStatement.executeQuery();

        } catch (SQLException e) {
            throw new SqlExecutionException(String.format("执行sql异常\n\tsql=%s,params=%s", sql, this.arrayToString(params)), e);
        }

        return resultSet;
    }

    /**
     * SQL 查询将查询结果：一行一列
     * 
     * @param sql SQL语句
     * @param params 参数数组，若没有参数则为null
     * @return 结果集
     */
    public Object executeQuerySingle(String sql, Object... params) throws SqlExecutionException {
        Object object = null;
        try {
            // 调用SQL
            preparedStatement = connection.prepareStatement(sql);
            if (queryTimeOut != -1) {
                preparedStatement.setQueryTimeout(queryTimeOut);
            }
            // 参数赋值
            if (params != null && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    preparedStatement.setObject(i + 1, transformType(params[i]));
                }
            }
            // 执行
            resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                object = resultSet.getObject(1);
            }

        } catch (Exception e) {
            throw new SqlExecutionException(e);
        } finally {
            closeAll();
        }

        return object;
    }

    /**
     * 获取结果集，并将结果放在List中 自动关闭连接
     * 
     * @param sql SQL语句
     * @return List 结果集
     */
    public List<Map<String, Object>> excuteQuery(String sql, Object... params) throws SqlExecutionException {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        // 结果集列数
        try {
            // 执行SQL获得结果集
            resultSet = executeQueryRS(sql, params);
            // 创建ResultSetMetaData对象
            ResultSetMetaData rsmd = resultSet.getMetaData();
            // 获得结果集列数
            int columnCount = rsmd.getColumnCount();
            // 将ResultSet的结果保存到List中
            while (resultSet.next()) {
                Map<String, Object> map = new HashMap<String, Object>();
                for (int i = 1; i <= columnCount; i++) {
                    if (!this.needRowNum && ROW_FLAG.equals(rsmd.getColumnLabel(i))) {
                        continue;
                    }
                    map.put(rsmd.getColumnLabel(i), resultSet.getObject(i));
                }
                list.add(map);
            }

        } catch (SQLException e) {
            throw new SqlExecutionException("\nsql=" + sql, e);
        } finally {
            // 关闭所有资源
            closeAll();
        }

        return list;
    }

    /**
     * 存储过程带有一个输出参数的方法
     * 
     * @param sql 存储过程语句
     * @param params 参数数组
     * @param paramPos 输出参数位置
     * @param sqlType 输出参数类型
     * @return 输出参数的值
     */
    public Object excuteQuery(String sql, Object[] params, int paramPos, int sqlType) throws SqlExecutionException {
        Object object = null;
        try {
            // 调用存储过程
            callableStatement = connection.prepareCall(sql);
            if (queryTimeOut != -1) {
                callableStatement.setQueryTimeout(queryTimeOut);
            }
            // 给参数赋值
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    callableStatement.setObject(i + 1, transformType(params[i]));
                }
            }
            // 注册输出参数
            callableStatement.registerOutParameter(paramPos, sqlType);
            // 执行
            callableStatement.execute();

            // 得到输出参数
            object = callableStatement.getObject(paramPos);

        } catch (SQLException e) {
            throw new SqlExecutionException(e);
        } finally {
            // 释放资源
            closeAll();
        }

        return object;
    }

    /**
     * 关闭所有资源
     */
    private void closeAll() {
        // 关闭结果集对象
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new SqlExecutionException(e);
            }
        }

        // 关闭PreparedStatement对象
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                throw new SqlExecutionException(e);
            }
        }

        // 关闭CallableStatement 对象
        if (callableStatement != null) {
            try {
                callableStatement.close();
            } catch (SQLException e) {
                throw new SqlExecutionException(e);
            }
        }

        if (connection != null) {
            try {
                connection.setAutoCommit(true);
            } catch (SQLException e) {
                throw new SqlExecutionException(e);
            }
            // 关闭Connection 对象
            /*try {
                connection.close();
            } catch (SQLException e) {
                throw new SqlExecutionException(e);
            }*/
        }
    }

    private String arrayToString(Object[] params) {
        return  StringUtils.join(params,",");
    }

    private Object transformType(Object value) {
        if (null == value) {
            return value;
        }
        if (value instanceof java.util.Date) {
            return new java.sql.Timestamp(((java.util.Date) value).getTime());
        } else {
            return value;
        }
    }
}